//
//  MagazineViewController.m
//  JianChaRiBao
//
//  Created by yuzhou on 13-5-13.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "MagazineViewController.h"
#import "MagazineCategoryCell.h"
#import "AppDelegate.h"
#import "MagazineCategoryWidget.h"
#import "MyCategoryCell.h"
#import "MagazineInfoViewController.h"
#import "MagazineShelfViewController.h"
#import "SearchViewController.h"
@interface MagazineViewController ()
{
    MagazineCategoryWidget *magazineCategoryWidget;
}
@property (nonatomic,retain) NSArray *categoryArray;
@end

@implementation MagazineViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CategoryCellDidSelect:) name:@"CategoryCellDidSelect" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MyCategoryCellClicked:) name:@"MyCategoryCellClicked" object:nil];
    }
    return self;
}
- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:categoryTableView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

-(void)loadView{
    [super loadView] ;
    mTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    mTableView = [[UITableView alloc]initWithFrame:categoryTableView.frame];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view insertSubview:mTableView atIndex:0];
//    [self loadCategory];

}
- (IBAction)searchBtnClicked:(id)sender {
    SearchViewController * searchViewController = [[[SearchViewController alloc]initWithNibName:@"SearchViewController" bundle:nil]autorelease];
    searchViewController.type = searchMagzine;
    [[UIApplication rootNavController] pushViewController:searchViewController animated:YES];
}
- (IBAction)showShelf:(id)sender {
    MagazineShelfViewController * magazineShelfViewController = [[MagazineShelfViewController alloc]initWithNibName:@"MagazineShelfViewController" bundle:nil];
    [[UIApplication rootNavController] pushViewController:magazineShelfViewController animated:YES];
}
-(void)loadCategory{
    if (magazineCategoryWidget == nil) {
        magazineCategoryWidget = [[MagazineCategoryWidget alloc] initWithFrame:CGRectMake(0, 0, 320, 548)];
        [magazineCategoryWidget updateCategory:_categoryArray key:@"name"];
    }
    if (magazineCategoryWidget.superview == nil) {
        [[UIApplication rootViewController] updateWidgetView:magazineCategoryWidget];
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    mDataArray = [[NSMutableArray alloc]initWithCapacity:0];
    self.view.frame = self.parentViewController.view.bounds;
    [self getData];
}
-(void)CategoryCellDidSelect:(NSNotification *)notification{
    
    [headImage setImage:[UIImage imageNamed:@"top_bar_bg.png"]];
    titleLabel.text = [notification.object objectForKey:@"name"];
    if (notification.object) {
        [mDataArray removeAllObjects];
        if (mTableView.superview) {
            [mTableView removeFromSuperview];
        }
        mTableView.frame = categoryTableView.frame;
        [self.view addSubview:mTableView];
        [self.view bringSubviewToFront:mTableView];
        [self showLoadingView];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSDictionary * dict = [[DataRequest sharedRequest] getMagazineByCatgory:[notification.object objectForKey:@"catid"]];
            NSArray * dataArray = [NSArray arrayWithArray:[dict objectForKey:@"result"]];
            
            int count = dataArray.count;
            for (int i = 0 ; i < count; i += 3) {
                NSMutableArray * array = [NSMutableArray array];
                [array addObject:[dataArray objectAtIndex:i]];
                if (i + 1 < count) {
                    [array addObject:[dataArray objectAtIndex:i + 1]];
                }
                if (i + 2 < count) {
                    [array addObject:[dataArray objectAtIndex:i + 2]];
                }
                [mDataArray addObject:array];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self removeloadingView];
                [mTableView reloadData];
            });
        });
    }else{
        [headImage setImage:[UIImage imageNamed:@"new_logo_top_bar.png"]];
        titleLabel.text = nil;
        [mTableView removeFromSuperview];
    }
}
-(void)MyCategoryCellClicked:(NSNotification *)notification{
    MagazineInfoViewController *magazineInfoViewController = [[[MagazineInfoViewController alloc] initWithNibName:@"MagazineInfoViewController" bundle:nil] autorelease];
    magazineInfoViewController.basicInfo = [notification object];
    [[UIApplication rootNavController] pushViewController:magazineInfoViewController animated:YES];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self loadCategory];
}

- (void)getData
{
    [self showLoadingView];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary *data = [[DataRequest sharedRequest] getMagazineCategory];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self removeloadingView];
            if (data && [data isKindOfClass:[NSDictionary class]] && [[data objectForKey:@"result"] isKindOfClass:[NSArray class]]) {
                self.categoryArray = [data objectForKey:@"result"];
                [categoryTableView reloadData];
                [magazineCategoryWidget updateCategory:_categoryArray key:@"name"];
                
            }
        });
    });
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == mTableView) {
        return mDataArray.count;
    }
    return _categoryArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == mTableView) {
        static NSString * cellID = @"cellID";
        MyCategoryCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"MyCategoryCell" owner:self options:nil]lastObject];
            
        }
        NSArray * array = [mDataArray objectAtIndex:indexPath.row];
        [cell setImageWitharray:array];
        
        return cell;
    }
    static NSString *CellIdentify = @"MagazineCategoryCell";
    MagazineCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentify];
    if (cell == nil) {
        cell = [[[MagazineCategoryCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentify] autorelease];
    }
    [cell setCategory:[_categoryArray objectAtIndex:indexPath.row]];
    return cell;

    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 155;
}

- (IBAction)showCategory
{
    [[UIApplication rootViewController] showWidgetView];
}

- (void)swipeBack
{
    [self showCategory];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [categoryView release];
    [mTableView release];
    [mDataArray release];
    
    [categoryTableView release];
    [_categoryArray release];
    [magazineCategoryWidget release];
    
    [titleLabel release];
    [headImage release];
    [super dealloc];
}
- (void)viewDidUnload {
    [categoryTableView release];
    categoryTableView = nil;
    [magazineCategoryWidget release];
    magazineCategoryWidget = nil;
    [titleLabel release];
    titleLabel = nil;
    [headImage release];
    headImage = nil;
    [super viewDidUnload];
}
@end
